﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TNX.Common.Legacy
{
    /// <summary>
    /// Cached AppdomainFunc
    /// </summary>
    /// <typeparam name="RQ"></typeparam>
    /// <typeparam name="RE"></typeparam>
    public class AppDomainContextSmartCached<RQ, RE> : AppDomainContextSmart<RQ, RE>, IDisposable
        where RQ : struct
        where RE : struct
    {
        public AppDomainContextSmartCached()
            : base()
        {
            Handler = (CrossDomainHandler)Domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(CrossDomainHandler).FullName);
        }
        
        protected readonly CrossDomainHandler Handler;

        public override void Dispose()
        {
            Handler.Dispose();
            base.Dispose();
        }

        public override RE ExecuteCrossDomainOperation(Func<RQ, RE> handler, RQ request)
        {
            bool result;
            Exception ex;

            var risp = Handler.Execute(handler, request, out result, out ex);

            if (result)
                return risp;
            else
                throw ex;
        }
    }
}
